package com.xzh.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xzh.gulimall.product.service.CategoryBrandRelationService;
import com.xzh.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzh.common.utils.PageUtils;
import com.xzh.common.utils.Query;

import com.xzh.gulimall.product.dao.CategoryDao;
import com.xzh.gulimall.product.entity.CategoryEntity;
import com.xzh.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    RedissonClient redissonClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构
        //2.1、找出所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{
            menu.setChildren(getChildren(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        //List<CategoryEntity> children2 = getChildren2(entities);
        return level1Menus;
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    //级联更新所有关联的数据
    /*
    * 失效模式*/
    //@CacheEvict(value = {"category"},key = "'getLevel1Categorys'")
    //同时进行多种缓存操作
    @Caching(evict = {
            @CacheEvict(value = {"category"},key = "'getLevel1Categorys'"),
            @CacheEvict(value = {"category"},key = "'getCatalogJson'")
    })
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    //每一个需要缓存的数据我们都来指定要放到哪个名字的缓存 【缓存分区(按照业务类型分)】
    /*
    * 默认行为
    *  1、如果缓存中有，方法不用调用
    *  2、key默认自动生成，缓存的名字::SimpieKey [](自主生成的key值）
    *  3、缓存的value值，默认使用jdk序列化机制，将序列化后的数据存到redis
    *  4、默认ttl时间 -1
    *
    * 自定义操作
    *  1、指定生成的缓存使用的key key属性指定，接收一个SpEL
    *  2、指定缓存的数据的存活时间 配置文件中修改ttl
    *  3、数据保存为json格式
    *      CacheAutoConfiguration 导入 RedisCacheConfiguration ，自动配置RedisCacheManager->初始化所有的缓存
    *      -》每个缓存决定使用什么配置->如果redisCacheConfiguration有就用已有的，没有就用默认配置->
    *      想改缓存的配置，只需要给容器中放一个RedisCacheConfiguration即可
    *      ->就会应用到当前的RedisCacheManager管理的所有缓存分区中
    * */
    @Cacheable(value = {"category"},key = "#root.methodName") //代表当前方法的结果需要缓存，如果缓存有，方法不用调用，如果缓存中没有，调用方法，将方法的结果放入缓存
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("方法调用");
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }

    //TODO:产生堆外内存溢出：  OutOfDirectMemoryError
    //1、springboot2.0之后默认使用lettuce作为操作redis的客户端，它使用netty进行网络通信。
    //2、lettuce的bug导致堆外内存溢出 -Xmx300m,netty如果没有指定对外内存，默认使用-xmx300m
    //3、可以通过-Dio.netty.maxDirectMemory进行设置

    //解决方案，不能使用-Dio.netty.maxDirectMemory只去调大对外内存
    //1、升级lettuce客户端
    //2、切换使用jedis
    //
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        /*
        1、空结果缓存，解决缓存穿透
        2、设置随机过期时间，解决缓存雪崩
        3、加锁，解决缓存击穿
        * */
        //给缓存中放json字符串，拿出json字符串，逆转为能用的对象类型。【序列化与反序列化】
        //加入缓存逻辑
        Map<String, List<Catelog2Vo>> catalogJSON = (Map<String, List<Catelog2Vo>>) redisTemplate.opsForValue().get("catalogJSON");
        if(catalogJSON==null||catalogJSON.isEmpty()){
            //缓存中没有，查询数据库
            Map<String, List<Catelog2Vo>> catalogJsonFromdb = getCatalogJsonFromdbWithRedisLock();
            //查到的数据放入缓存
            //redisTemplate.opsForValue().set("catalogJSON",catalogJsonFromdb,1, TimeUnit.DAYS);
            return catalogJsonFromdb;
        }
        return catalogJSON;
    }

    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有1级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找到当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parent_cid;
    }


    /*
    * 缓存中的数据如何与数据库中的数据保持一致
    * 缓存数据一致性
    * 1）、双写模式
    * 2）、失效模式*/
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromdbWithRedissonLock() {
        RLock lock = redissonClient.getLock("CatalogJson-lock");
        lock.lock();
        System.out.println("获取分布式锁成功====");
        Map<String, List<Catelog2Vo>> datafromDb;
        //加锁成功
        try {
            datafromDb = getDatafromDb();
        } finally {
           lock.unlock();
        }
        return datafromDb;

    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromdbWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        if(lock){
            System.out.println("获取分布式锁成功====");
            Map<String, List<Catelog2Vo>> datafromDb;
            //加锁成功
            try {
                datafromDb = getDatafromDb();
            }finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return  redis.call('del', KEYS[1]) else return 0 end";
                //删除锁
                System.out.println("删除锁之前===？");
                stringRedisTemplate.execute(new DefaultRedisScript(script, Long.class)
                        , Arrays.asList("lock"), uuid);
                System.out.println("删除锁之后===");
            }
            return datafromDb;
        }else{
            //加锁失败 。。重试
            System.out.println("获取分布式锁失败====重试");
            return getCatalogJsonFromdbWithRedisLock(); //自旋的方式
        }
    }
    //从数据库查询分类数据
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromdbWithLocalLock(){
        synchronized (this){
            return getDatafromDb();
        }
    }

    public Map<String, List<Catelog2Vo>> getDatafromDb() {
        Map<String, List<Catelog2Vo>> catalogJSON = (Map<String, List<Catelog2Vo>>) redisTemplate.opsForValue().get("catalogJSON");
        if (catalogJSON != null && !catalogJSON.isEmpty()) {
            return catalogJSON;
        }
        System.out.println("==查询数据库==");
        /*
         * 1、将数据库的多次查询变成一次*/
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有1级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找到当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        redisTemplate.opsForValue().set("catalogJSON", parent_cid, 1, TimeUnit.DAYS);
        return parent_cid;
    }


    List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parent_cid)
    {
        List<CategoryEntity> collect = selectList.stream().filter(item -> {
            return item.getParentCid().equals(parent_cid);
        }).collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点Id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

    //以下为我自己的方法，通过建图然后递归查询
    class A{
        private int nxt,v;
        public A(int nxt,int v)
        {
            this.nxt=nxt;
            this.v=v;
        }
    }
    private int [] head = new int[100010];
    private A [] edge = new A[100010];
    private int cnt = 0;
    private void add(Long U,Long V)
    {
        int u = U.intValue();
        int v = V.intValue();
        edge[++cnt] = new A(head[u],v);
        //edge[++cnt].setNxt(head[u]);//将头边传递
        //edge[cnt].setV(v);
        head[u]=cnt;//头边更新
    }
    private void dfs(Long U,List<CategoryEntity> all)
    {
        int u = U.intValue();
        for(int i = head[u];i!=-1;i=edge[i].nxt)
        {
            Integer V = edge[i].v;
            long v = V.longValue();
            all.get(u-1).setChild(all.get(V-1));
            dfs(v,all);
        }
    }
    private List<CategoryEntity> getChildren2(List<CategoryEntity> all)
    {
        System.out.println(all.size());
        for (CategoryEntity categoryEntity : all) {
            System.out.println(categoryEntity.getCatId());
        }
        for(int i=0;i<100000;++i) head[i]=-1;
        for (CategoryEntity categoryEntity : all) {
            if(categoryEntity.getParentCid()!=null&&categoryEntity.getParentCid()!=0) {
                add(categoryEntity.getParentCid(),categoryEntity.getCatId());
            }
        }
        List<CategoryEntity> root = new ArrayList<>();
        for (CategoryEntity categoryEntity : all) {
            if(categoryEntity.getParentCid()==0)
            {
                dfs(categoryEntity.getCatId(), all);
                root.add(categoryEntity);
            }
        }
        return root;
    }

}